package com.ysd.ServiceImpl;

import java.util.List;
import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ysd.Service.RolesService;
import com.ysd.entity.UserInfo;
import com.ysd.entity.roles;
import com.ysd.repository.RolesRepository;
import com.ysd.repository.UserInfoRepository;
@Service
public class RolesServiceImpl implements RolesService {
@Autowired
private RolesRepository rolesRepository;
@Autowired
private UserInfoRepository userRepository;
	@Override
	public List<roles> findAllRoles() {
		// TODO Auto-generated method stub
		return rolesRepository.findAll();
	}
	@Override
	public Optional<UserInfo> findByIDfindRoles(String userid) {
		// TODO Auto-generated method stub
		return   userRepository.findById(userid);
	}
	@Override
	public Page<roles> findAllRoles(roles r, Pageable pageable) {
		// TODO Auto-generated method stub
		return rolesRepository.findAll(get(r), pageable);
	}
	private Specification<roles> get(roles r) {
		// TODO Auto-generated method stub
		return new Specification<roles>() {

			@Override
			public Predicate toPredicate(Root<roles> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate predicate = criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				if (r.getRname()!=null && r.getRname()!="") {//角色名称
					expressions.add(criteriaBuilder.like(root.get("rname"),"%"+r.getRname()+"%" ));
					}
				if (r.getDescription()!=null && r.getDescription()!="") {//角色职位
					expressions.add(criteriaBuilder.like(root.get("description"),"%"+r.getDescription()+"%" ));
					}
				return predicate;
			}
		};
	}
	@Override
	public roles addAndUpdate(roles r) {
		// TODO Auto-generated method stub
		return rolesRepository.saveAndFlush(r);
	}
	@Override
	public void deleteRoles(roles roles) {
		// TODO Auto-generated method stub
		rolesRepository.delete(roles);
	}
	/**
	 * 查询某个角色信息    用于设置角色模块
	 */
	@Override
	public Optional<roles> ByidfindModules(String Id) {
		// TODO Auto-generated method stub
		return rolesRepository.findById(Id);
	}
	/**
	 *给角色模块中间表添加数据
	 */
	@Override
	public void saveModulesrole(String rid, Integer mid) {
		// TODO Auto-generated method stub
		rolesRepository.saveModulesrole(rid, mid);
	}
	/**
	 * 根据角色id删除中间表的模块
	 */
	@Override
	public void delModulesrole(String rid) {
		// TODO Auto-generated method stub
		rolesRepository.delModulesrole(rid);
	}

	
	

}
